package com.android.manghe.box.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.android.base.frame.title.ETitleType;
import com.android.base.frame.view.MVPActivity;
import com.android.base.tools.ToastUtil;
import com.android.manghe.R;
import com.android.manghe.box.adapter.GiftUltraPagerAdapter;
import com.android.manghe.box.adapter.GiftsResultAdapter2;
import com.android.manghe.box.model.BoxGiftModel;
import com.android.manghe.box.model.BoxModel;
import com.android.manghe.box.model.MessageEvent;
import com.android.manghe.box.presenter.PUnpackingFive;
import com.android.manghe.common.model.ShowBoxEvent;
import com.android.manghe.config.Config;
import com.android.manghe.utils.WindowUtils;
import com.android.manghe.view.FiveGiftLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.eightbitlab.rxbus.Bus;
import com.tencent.mm.opensdk.utils.Log;
import com.tmall.ultraviewpager.UltraViewPager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * author : liuwen
 * e-mail : liuwen370494581@163.com
 * time   : 2021/11/16 10:09
 * desc   : 开箱 五连抽
 */
public class UnpackingFiveActivity extends MVPActivity<PUnpackingFive> {

    private ImageView mImgGift, mImgBg;
    private String mGiftSort;
    private View mFiveView, mTwoAndThreeView, mTenView;
    private TextView mTvChange, mTvAgain, mTvGoBox, mTvWay;
    private FiveGiftLayout mFiveGiftLayout;
    private UltraViewPager mViewPager;
    private GiftUltraPagerAdapter mUltraPagerAdapter;

    private RecyclerView mRecyclerView;
    private GiftsResultAdapter2 mAdapter2;

    private RecyclerView mRecyclerViewTen1, mRecyclerViewTen2;
    private GiftsResultAdapter2 mAdapterTen1, mAdapterTen2;
    private RelativeLayout mLayoutTitle;
    private int mOrderId;
    private MediaPlayer mediaPlayer;
    private int mPayCount, payWay;

    private BoxModel.DataBean mCurrentBox;
    private AnimatorSet animatorSet;

    @Override
    protected ETitleType showToolBarType() {
        return ETitleType.NO_TITLE;
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        WindowUtils.hideStatusBar(this);
        mImgGift = findViewById(R.id.id_img_gift);
        mViewPager = findViewById(R.id.bannerViewPager);
        mCurrentBox = (BoxModel.DataBean) getIntent().getSerializableExtra("BoxListModel");
        mOrderId = getIntent().getIntExtra("orderId", 0);
        mPayCount = getIntent().getIntExtra("PayCount", 0);
        payWay = getIntent().getIntExtra("PayPageWay", 0);
        mImgBg = findViewById(R.id.id_img_bg);
        mTvWay = findViewById(R.id.id_tv_way);
        mLayoutTitle = findViewById(R.id.id_re_title);

        mTwoAndThreeView = findViewById(R.id.id_open_box_two_three);
        mFiveView = findViewById(R.id.id_open_box_five);
        mTenView = findViewById(R.id.id_open_box_ten);
        mImgBg.setScaleX(2.5f);
        mImgBg.setScaleY(2.5f);
        animatorSet = new AnimatorSet();
        Glide.with(this)
                .load(mCurrentBox.cover_pic)
                .crossFade()
                .into(new SimpleTarget<GlideDrawable>() {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                        mImgGift.setImageDrawable(resource);
                        startAnimator();
                    }
                });

        switch (mPayCount) {
            case 2:
                initViewCommon(mTwoAndThreeView);
                initTwoAndThreeView(mTwoAndThreeView);
                mTvWay.setText("二连抽");
                break;
            case 3:
                initViewCommon(mTwoAndThreeView);
                initTwoAndThreeView(mTwoAndThreeView);
                mTvWay.setText("三连抽");
                break;
            case 5:
                initViewCommon(mFiveView);
                initFiveView(mFiveView);
                mTvWay.setText("五连抽");
                break;
            case 10:
                initViewCommon(mTenView);
                initTenView(mTenView);
                mTvWay.setText("十连抽");
                break;
            default:
                mTvWay.setText("");
                break;
        }

        mImgGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getP().getBoxOpen(mOrderId);
            }
        });

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                starFreshenAnimation(mImgBg);
                getP().getBoxOpen(mOrderId);
            }
        }, 100);
    }

    public void startPlay(int rawRes, boolean isLoop) {
        try {
            stopPlay();
            mediaPlayer = MediaPlayer.create(this, rawRes);
            mediaPlayer.setLooping(isLoop);
            mediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopPlay() {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                Log.e("MainActivity", "Unpack=======" + "  mediaPlayer.stop()");
                mediaPlayer.release();
                Log.e("MainActivity", "Unpack=======" + "  mediaPlayer.release()");
                mediaPlayer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        WindowUtils.hideStatusBar(this);
    }

    private void starFreshenAnimation(ImageView imageView) {
        Animation circle_anim = AnimationUtils.loadAnimation(this, R.anim.anim_round_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();  //设置匀速旋转，在xml文件中设置会出现卡顿
        circle_anim.setInterpolator(interpolator);
        imageView.startAnimation(circle_anim);  //开始动画
    }

    private void initFiveView(View view) {
        mFiveGiftLayout = view.findViewById(R.id.id_five_gift_layout);
    }

    private void initTwoAndThreeView(View view) {
        mRecyclerView = view.findViewById(R.id.id_recycler_view);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, mPayCount);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mAdapter2 = new GiftsResultAdapter2(this, new ArrayList<>());
        mRecyclerView.setAdapter(mAdapter2);

    }

    private void initTenView(View view) {
        mRecyclerViewTen1 = view.findViewById(R.id.id_recycler_view_2);
        mRecyclerViewTen2 = view.findViewById(R.id.id_recycler_view_3);

        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this);
        linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);

        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(this);
        linearLayoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);


        mRecyclerViewTen1.setLayoutManager(linearLayoutManager1);
        mRecyclerViewTen2.setLayoutManager(linearLayoutManager2);

        mAdapterTen1 = new GiftsResultAdapter2(this, new ArrayList<>());
        mAdapterTen2 = new GiftsResultAdapter2(this, new ArrayList<>());

        mRecyclerViewTen1.setAdapter(mAdapterTen1);
        mRecyclerViewTen2.setAdapter(mAdapterTen2);
    }

    private void initViewCommon(View view) {
        mTvAgain = view.findViewById(R.id.id_tv_again);
        mTvChange = view.findViewById(R.id.id_tv_change);
        mTvGoBox = view.findViewById(R.id.id_tv_go_box);

        mTvChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //通转到盒柜页面
                Bus.INSTANCE.send(new ShowBoxEvent());
                EventBus.getDefault().post(new MessageEvent(Config.EVENT_BUS_CLOSE_ACTIVITY));
                finish();
            }
        });

        mTvAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MessageEvent(Config.EVENT_BUS_SHOW_ORDER, mPayCount, payWay));
                finish();

            }
        });
        setColorAndEvent();
    }


    private void setColorAndEvent() {
        SpannableStringBuilder style = new SpannableStringBuilder("前往");
        SpannableStringBuilder style2 = new SpannableStringBuilder("盒柜");
        SpannableStringBuilder style3 = new SpannableStringBuilder("，选择申请发货");
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.yellow500));
        setTextClickEvent(style2, 0, style2.length());
        style2.setSpan(foregroundColorSpan, 0, style2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.append(style2).append(style3);

        mTvGoBox.setMovementMethod(LinkMovementMethod.getInstance());
        mTvGoBox.setText(style);
    }

    private void setTextClickEvent(SpannableStringBuilder style, int start, int end) {
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                //跳转到盒柜页面
                Bus.INSTANCE.send(new ShowBoxEvent());
                EventBus.getDefault().post(new MessageEvent(Config.EVENT_BUS_CLOSE_ACTIVITY));
                finish();

            }
        };
        style.setSpan(clickableSpan1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }


    public void updateDate(List<BoxGiftModel.ListBean> list) {
        //提醒盒柜刷新
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (UnpackingFiveActivity.this.isFinishing()) {
                    return;
                }
                startPlay(R.raw.open_box_2, false);
                animatorSet.cancel();
                EventBus.getDefault().post(new MessageEvent(Config.EVENT_BUS_OPEN_SUCCESS));
                // Bus.INSTANCE.send(new RefreshIndexNoticeEvent());
                mLayoutTitle.setVisibility(View.GONE);
                mImgGift.setVisibility(View.GONE);
                mViewPager.setVisibility(View.VISIBLE);

                //为了判断是开盒的结果
                if ((mPayCount == 2 && list.size() == 2) || (mPayCount == 3 && list.size() == 3)) {
                    mAdapter2.replaceData(list);
                } else if (mPayCount == 5 && list.size() == 5) {
                    showLastView(list);
                } else if (mPayCount == 10 && list.size() == 10) {
                    mAdapterTen1.replaceData(list.subList(0, 5));
                    mAdapterTen2.replaceData(list.subList(5, 10));
                }
                mUltraPagerAdapter = new GiftUltraPagerAdapter(UnpackingFiveActivity.this, list);
                mViewPager.setAdapter(mUltraPagerAdapter);
                if (list.size() > 0) {
                    mViewPager.setAutoScroll(1500);
                    mViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
                } else {
                    mViewPager.setInfiniteLoop(false);
                }
                mViewPager.setCurrentItem(0);
                mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    }

                    @Override
                    public void onPageSelected(int position) {
                        if (mPayCount == 2 && list.size() == 2) {
                            if (position == 1) {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        mViewPager.setInfiniteLoop(false);
                                        mViewPager.disableAutoScroll();
                                        mViewPager.setVisibility(View.GONE);
                                        mTwoAndThreeView.setVisibility(View.VISIBLE);
                                    }
                                }, 1500);
                            }

                        } else if (mPayCount == 3 && list.size() == 3) {
                            if (position == 2) {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        mViewPager.setInfiniteLoop(false);
                                        mViewPager.disableAutoScroll();
                                        mViewPager.setVisibility(View.GONE);
                                        mTwoAndThreeView.setVisibility(View.VISIBLE);
                                    }
                                }, 1500);
                            }

                        } else if (mPayCount == 5 && list.size() == 5) {
                            if (position == 4) {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        mViewPager.setInfiniteLoop(false);
                                        mViewPager.disableAutoScroll();
                                        mViewPager.setVisibility(View.GONE);
                                        mFiveView.setVisibility(View.VISIBLE);
                                    }
                                }, 1500);
                            }
                        } else if (mPayCount == 10 && list.size() == 10) {
                            if (position == 9) {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        mViewPager.setInfiniteLoop(false);
                                        mViewPager.disableAutoScroll();
                                        mViewPager.setVisibility(View.GONE);
                                        mTenView.setVisibility(View.VISIBLE);
                                    }
                                }, 1500);
                            }
                        }


                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                    }
                });

            }
        }, 2000);

    }

    /**
     * 显示五个盒子
     *
     * @param list
     */
    private void showLastView(List<BoxGiftModel.ListBean> list) {
        mFiveGiftLayout.update(list);
    }


    public void setFailureTip(String context) {
        ToastUtil.showLong(this, context);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_unpacking_five;
    }

    /**
     * 开启动画
     */
    private void startAnimator() {
        ObjectAnimator animatorX = ObjectAnimator.ofFloat(mImgGift, "scaleX", 1f, 1.2f, 1f);
        ObjectAnimator animatorY = ObjectAnimator.ofFloat(mImgGift, "scaleY", 1f, 1.2f, 1f);
        animatorX.setRepeatCount(ValueAnimator.INFINITE);
        animatorY.setRepeatCount(ValueAnimator.INFINITE);
        animatorSet.setDuration(700);
        animatorSet.play(animatorX).with(animatorY);
        animatorSet.start();
        startPlay(R.raw.open_box_1, true);
    }


    @Override
    public void onBackPressed() {
        stopPlay();
        mImgBg.clearAnimation();
        animatorSet.cancel();
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlay();
        mImgBg.clearAnimation();
        animatorSet.cancel();
    }
}
